const express = require("express");
const router = express.Router();
const path = require("path");
const multer = require("multer");
const upload = multer({ dest: path.join(__dirname, "../../../public/images") });

const { timeTrans } = require("../../../utils");
const {
  getTopic,
  delTopic,
  setShow,
  addTopic,
  setTopic,
  delTopicAll,
} = require("../../../model/weixin/admin/questionbank");
// 请求questionbank
router.get("/", async function (req, res) {
  let data = await getTopic();
  console.log(data);
  res.send(data);
});
// 删除
router.post("/del", async function (req, res) {
  const id = Number(req.body.id);
  console.log(id);
  delTopic([id])
    .then(() => {
      res.send({
        code: 200,
        msg: "删除成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "删除失败",
      });
    });
});
// 修改上架
router.post("/setShow", async function (req, res) {
  let id = req.body.id;
  let isShow = req.body.isShow === "false" ? 0 : 1;

  setShow([isShow, id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改成功",
      });
    })
    .catch((err) => {
      console.log(err);
    });
});
// 添加
router.post("/addTopic", function (req, res) {
  const id = Number(req.body.id);
  const src =
    "http://localhost:3333/images/" + req.body["src[name]"] ||
    req.body["src[name]"];
  const atime = timeTrans(req.body.atime);
  const title = req.body.title;
  const number = req.body.number;
  addTopic([src, title, number, atime])
    .then(() => {
      res.send({
        code: 200,
        msg: "添加成功",
      });
    })
    .catch((err) => {
      res.send({
        code: 500,
        msg: "添加失败",
      });
    });
});
// 修改一项
router.post("/setTopic", async function (req, res) {
  console.log(req.body);
  const id = Number(req.body.id);
  const src =
    "http://localhost:3333/images/" + req.body["src[name]"] ||
    req.body["src[name]"];
  const atime = timeTrans(req.body.atime);
  const title = req.body.title;
  const number = req.body.number;
  setTopic([src, title, number, atime, id])
    .then(() => {
      res.send({
        code: 200,
        msg: "修改成功",
      });
    })
    .catch((err) => {});
});
router.get("/allDel", async function (req, res) {
  console.log(req.query.data);
  let data = req.query.data;
  let dataLength = data.length;
  for (let i = 0; dataLength; i++) {
    await delTopic([data[i]]);
  }

  res.send({
    code: 200,
    msg: "删除成功",
  });
});
module.exports = router;
